#! /usr/bin/env python
from pywslib import *
import sys
pyws = pywslib()
pyws.header()

logfile = "www/rubrica.log"

def build_rub(logfile):
	ret = {}
	try:
		file = open(logfile,"r")
	except:
		print "Impossibile aprire il file log"
		sys.exit()
	while True:
		read = file.readline(1024).rstrip().split(";")
		if read == ['']:
			break
		ret[read[3]] = {"nome":read[0],"tel":read[1],"ind":read[2]}
	return ret


def rebuild_rub(logfile,rub):
	file = open(logfile,"w")
	i = 0
	for elm in rub:
		i = i + 1
		file.write(str(rub[elm]["nome"])+";"+str(rub[elm]["tel"])+";"+str(rub[elm]["ind"])+";"+str(i)+"\n")
	file.close()
	
def top():
	print '''
	<a href='rubrica.py?act=c'>Cerca</a> - <a href='rubrica.py?act=l'>Lista</a> - <a href='rubrica.py?act=i'>Inserisci</a><hr><br />
	'''


rub = build_rub(logfile)
try:
	act = pyws.GET["act"]
except:
	act = ""

try:
	act2 = pyws.POST["act2"]
except:
	act2 = ""



top()


if act2 == "i":
	i = str(int(str(len(rub)))+1)
	try:
		nome = pyws.POST["nome"]
		tel = pyws.POST["tel"]
		ind = pyws.POST["ind"]
	except:
		print "Errore nei dati"
		sys.exit()
	rub[i] = {"nome":nome,"tel":tel,"ind":ind}
	rebuild_rub(logfile,rub)
	print "Aggiunto, Torna <a href='rubrica.py'>Indietro</a>"
	
if act2 == "s":
	try:
		key = pyws.POST["key"]
	except:
		print "Errore nei dati"
		sys.exit()
		print "<ul>"
	for elm in rub:
		if rub[elm]["nome"].find(key) > -1:
			print "<li><a href='rubrica.py?act=v&id="+elm+"'>"+rub[elm]["nome"]+"</a><br /></li>"
	print "</ul>"

if act == "i":
	print '''
	<form action='rubrica.py' method=POST>
	<input type='hidden' name='act2' value='i'>
	Nome e cognome : <input type='text' name='nome'><br />
	Telefono : <input type='text' name='tel'><br />
	Indirizzo : <input type='text' name='ind'><br />
	<input type='submit' value='Inserisci'>
	'''
	
if act == "l":
	print "<ul>"
	for elm in rub:
		print "<li><a href='rubrica.py?act=v&id="+elm+"'>"+rub[elm]["nome"]+"</a><br /></li>"
	print "</ul>"
	
if act == "v":
	try:
		id = pyws.GET["id"]
	except:
		print "Necessario ID"
		sys.exit()
	print "Nome: <b>"+rub[id]["nome"]+"</b><br />"
	print "Telefono: <b>"+rub[id]["tel"]+"</b><br />"
	print "Indirizzo: <b>"+rub[id]["ind"]+"</b><br />"

if act == "c":
	print '''
	<form action='rubrica.py' method='POST'>
	<input type='hidden' name='act2' value='s'>
	Cerca : <input type='text' name='key'><input type='submit' value='Cerca'></form>
	'''
	
